package com.neusoft.elm_servlet.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.neusoft.elm_servlet.dao.CartDao;
import com.neusoft.elm_servlet.dao.OrdersDao;
import com.neusoft.elm_servlet.dao.impl.CartDaoImpl;
import com.neusoft.elm_servlet.dao.impl.OrdersDaoImpl;
import com.neusoft.elm_servlet.po.Cart;
import com.neusoft.elm_servlet.po.OrderDetailet;
import com.neusoft.elm_servlet.po.Orders;
import com.neusoft.elm_servlet.service.OrdersService;
import com.neusoft.elm_servlet.util.DBUtil;

public class OrdersServiceImpl implements OrdersService {

	OrdersDao ordersDao = new OrdersDaoImpl();
	
	CartDao cartDao = new CartDaoImpl();
	
	@Override
	public int createOrders(Orders orders) throws SQLException {
		int orderId =0;
		
		try {
			//1.开启事务
			DBUtil.beginTranscation();
			//2.生成订单，调用Dao层，返回值为自增长id
			orderId = ordersDao.createOrders(orders);
			//3.根据用户和商家编号查询购物车数据
			List<Cart> listCart = cartDao.listCart(orders.getUserId(),orders.getBusinessId().toString());
			//4.批量插入生成订单明细数据
			ordersDao.createOrderDetailet(listCart,orderId);
			//5.清空购物车
			Cart cart = new Cart();
			cart.setUserId(orders.getUserId());
			cart.setBusinessId(orders.getBusinessId());
			cartDao.removeCart(cart);
			//6.事务提交/回滚
			DBUtil.commit();
		} catch (Exception e) {
			DBUtil.rollback();
			orderId = 0;
		} finally {
			DBUtil.closeCon();
		}
		
		return orderId;
	}

	@Override
	public Orders getOrdersById(String orderId) throws SQLException {
		//先获取订单和商家信息
		Orders orders = ordersDao.getOrdersById(orderId);
		
		//再根据订单编号获取订单明细数据
		List<OrderDetailet> orderDetailet = ordersDao.getOrderDetailetByOrderId(orderId);
		
		orders.setListOrderDetailet(orderDetailet);
		
		return orders;
	}

	@Override
	public List<Orders> listOrdersByUserId(String userId) throws SQLException {
		//先获取订单列表
		List<Orders> list = ordersDao.listOrdersByUserId(userId);
		
		for(Orders item:list){
			//再根据订单编号获取订单明细数据
			List<OrderDetailet> orderDetailet = ordersDao.getOrderDetailetByOrderId(item.getOrderId().toString());
			
			item.setListOrderDetailet(orderDetailet);		
		}
		return list;
	}}
